<?php

namespace App\Http\Controllers\Admin;

use App\Models\Areas;
use App\Models\BrandModel;
use App\Models\CategoryUser;
use App\Models\Goods;
use App\Models\GoodsClass;
use App\Models\GoodsCustomfield;
use App\Models\GoodsCustomRent;
use App\Models\GoodsHuabei;
use App\Models\GoodsCustom;
use App\Models\GoodsLog;
use App\Models\GoodsRentMealRel;
use App\Models\GoodsRentSku;
use App\Models\GoodsRentSpecRel;
use App\Models\GoodsSetmeal;
use App\Models\GoodsSpec;
use App\Models\GoodsType;
use App\Models\MemberPromise;
use App\Models\ShopUser;
use App\Requests\Admin\Goods\GoodsSaveRequest;
use App\Services\AlipayService;
use Illuminate\Http\Request;
use App\Services\CommonService;
use App\Services\GoodsService;
use Illuminate\Support\Facades\Redis;

class GoodsController extends BaseController
{
    /**
     * 获取商品列表
     */
    public function getGoodsList(Request $request){
        $data = $request->input();
        $list = Goods::AdminGoodsList($data);
        if($list){
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['status_name'] = GoodsService::getGoodsStatusName($v['status']);
            }
        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$list);
    }

    /**
     * 查看商品详情
     */
    public function getGoodsInfo(Request $request){
        $goods_id = $request->input('goods_id');
        if($goods_id){
            $goods = Goods::getGoodsInfo($goods_id);
            if($goods){
                $goods['new_grade'] = GoodsService::getGoodsNewGrade($goods['new_grade']);
                $goods['status_name'] = GoodsService::getGoodsStatusName($goods['status']);
                unset($goods['status']);

            }
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$goods);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'缺少参数');
        }
    }

    /**
     * 获取商户品类
     */
    public function getShopCategory(Request $request){
        $goods_id = $request->input('goods_id');
        if($goods_id){
            $goods = Goods::where('id',$goods_id)->select('member_id')->first();
            $goods = $goods ? $goods->toArray() : array();
            $member_id = $goods['member_id'];
            if(!empty($member_id)){
                $category = CategoryUser::GetShopCategory($member_id);
            }else{
                $category = [];
            }
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$category);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'缺少参数');
        }

    }


    /**
     * 获取商品参数
     */
    public function getGoodsParameter(Request $request){
       return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功');
    }


    /**
     * 获取商品添加各参数列表
     */
    public function getGoodsRentData(){
        $data = [];
        $data['new_grade'] = GoodsService::GOODS_NEW_GRADE_NAME_LIST;
        $data['rent_label'] = GoodsService::GOODS_RENT_LABEL_NAME_LIST;
        $data['pact_type'] = GoodsService::GOODS_PACT_TYPE_NAME_LIST;
        $data['send_out'] = GoodsService::GOODS_SEND_CONVEY_TYPE_NAME_LIST;
        $data['return'] = GoodsService::GOODS_RETURN_CONVEY_TYPE_NAME_LIST;

        $shop_user = $this->users;
        $member_id = $shop_user['user_id'];
        $data['goods_class'] = GoodsClass::getAll();
        $data['goods_brand'] = BrandModel::getAll();
        $data['goods_type'] = GoodsType::getAll();
        $data['shop_user'] = ShopUser::getShopUsers();


        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$data);
    }

    /**
     * 获取商品服务城市
     */
    public function getGoodsAreas(){
        $data = Areas::GetAreasList();
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$data);
    }

    /**
     * 编辑商品 -- 获取商品基础信息
     */
    public function getGoodsData(Request $request){
        $goods_id = $request->input('goods_id');
        if(!empty($goods_id)){
            $goods = Goods::getGoodsInfo($goods_id);
            if(!empty($goods)){
                $goods['attribute'] = GoodsCustom::getGoodsAttribute($goods_id);
            }
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$goods);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要编辑的商品');
        }
    }

    /**
     * 编辑商品基础信息
     */
    public function editGoodsData(GoodsSaveRequest $request){
        $data = $request->validated();
        if(empty($data['goods_id'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要编辑的商品');
        }
        $shop_user = $this->users;
        $res = Goods::EditGoodsData($data);
        if($res['status'] == CommonService::HTTP_CODE_SUCCESS){
            GoodsLog::AddGoodsLog($shop_user['id'],$data['goods_id'],'','编辑商品基础信息:'.$res['data']['operation_explain'],json_encode($data));
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'编辑成功',$res['data']);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, $res['msg']);
        }
    }


    /**
     * 获取起租日列表和租期间隔
     */
    public function getParameterList(){
        $data = [];
        $data['start_date'] = GoodsService::GOODS_START_DATE_LIST;
        $data['withhold_cycle'] = GoodsService::GOODS_WITHHOLD_CYCLE_LIST;
        $data['lease_term_month'] = GoodsService::GOODS_LEASE_TERM_MONTH_LIST;
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$data);
    }


    /**
     * 添加套餐信息
     */
    public function addSetmeal(Request $request){
        $data = $request->input();
        $goods = Goods::where('id',$request['goods_id'])->select('id','status')->first();
        $goods = $goods ? $goods->toArray() : [];
        if(!empty($goods)){
            $res = Goods::DealGoodsMealSpecData($data);
            if($res){
                //平台商品上架中编辑，状态改为已下架
                if($goods['status'] == GoodsService::GOODS_STATUS_PUT){
                    Goods::where('id',$request['goods_id'])->update(['status'=>GoodsService::GOODS_STATUS_OFF]);
                }
                GoodsLog::AddGoodsLog($this->users['id'],$data['goods_id'],$res['data']['setmeal_id'],'添加套餐信息',json_encode($data));
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'添加成功',$res['data']);
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, $res['msg']);
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '商品不存在');
        }

    }

    /**
     * 编辑商品套餐信息
     */
    public function editGoodsSetmeal(Request $request){
        $data = $request->input();
        $goods = Goods::where('id',$request['goods_id'])->select('id','status','open_sale')->first();
        $goods = $goods ? $goods->toArray() : [];
        if(!empty($goods)){
            $res = Goods::DealGoodsMealSpecData($data,$goods);
            if($res){
                //平台商品上架中编辑，状态改为已下架
                if($goods['status'] == GoodsService::GOODS_STATUS_PUT){
                    Goods::where('id',$request['goods_id'])->update(['status'=>GoodsService::GOODS_STATUS_OFF]);
                }
                GoodsLog::AddGoodsLog($this->users['id'],$data['goods_id'],$data['goods_id'],'编辑商品套餐信息',json_encode($data));
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'编辑成功',$res['data']);
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, $res['msg']);
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '商品不存在');
        }

    }
    /**
     * 编辑套餐 --- 获取商品套餐列表
     */
    public function getGoodsSetmealList(Request $request){
        $goods_id = $request->input('goods_id');
        if(!empty($goods_id)){
            $goods = Goods::where('id',$goods_id)->select('id','title')->first();
            $goods = $goods ? $goods->toArray() : array();
            if(!empty($goods)){
                $data = Goods::rentGoodsMealSpecInfo($goods_id);
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$data);
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '商品信息不存');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要编辑的商品');
        }
    }

    /**
     * 编辑套餐---获取套餐信息
     */
    public function getGoodsSetmealInfo(Request $request){
        $setmeal_id = $request->input('setmeal_id');
        if(!empty($setmeal_id)){
            $goods_setmeal = GoodsSetmeal::getGoodsSetmealInfo($setmeal_id);
            if($goods_setmeal){
                $goods = Goods::where('id',$goods_setmeal['goods_id'])->select('id','pact_type')->first();
                $goods = $goods ? $goods->toArray() : array();
                if(!empty($goods)){
                    $goods_setmeal['pact_type'] = $goods['pact_type'];
                }
                $spec = GoodsSpec::GetSpecList($setmeal_id,$goods['id']);
                if($goods_setmeal['lease_set'] == GoodsService::GOODS_RENT_TYPE_CUSTOM){//自定义租期
                    $custom = [];
                    foreach ($spec as $k=>$v){
                        $custom[] = GoodsCustomRent::GetCustomRent($v['id']);
                    }
                    $goods_setmeal['spec'] = $custom;
                }else{
                    $goods_setmeal['spec'] = $spec;
                }
                if($goods_setmeal['is_huabei'] == GoodsService::GOODS_SETMEAL_IS_HUABEI){
                    $goods_setmeal['huabei_data'] = GoodsHuabei::GetHuabeiList($setmeal_id);
                }
            }
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$goods_setmeal);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要编辑的套餐');
        }
    }



    /**
     * 商品分享
     */
    public function goodsShare(Request $request)
    {
        $goods_id = $request->input('goods_id');
        if ($goods_id) {
            $goods = Goods::where([['id', $goods_id], ['status', GoodsService::GOODS_STATUS_PUT], ['is_delete', GoodsService::GOODS_NO_DELETE_STATUS]])->select('id', 'title', 'imgurl', 'min_price')->first();
            $goods = $goods ? $goods->toArray() : array();
            if (!empty($goods)) {
                $imageInfo = getimagesize(config('alipay.oss.imgHost') . $goods['imgurl']);
                $goods['imgurl'] = 'data:' . $imageInfo['mime'] . ';base64,' . chunk_split(base64_encode(file_get_contents(config('alipay.oss.imgHost') . $goods['imgurl'])));
                $goods['alipay_url'] = config('alipay.xxz.alipayUrl') . 'pagesA/pages/productDetails/productDetails&query=goodsId=' . $goods_id . '&from=qrcode';
                $res = AlipayService::createQrCode(10001, $goods_id, $goods['title']);
                if ($res['status']) {
                    $goods['qrcode_url'] = $res['data']['qr_code_url'];
                }
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $goods);
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '上架中的商品才能分享');
            }
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择商品');
        }
    }


    /**
     * 商品下架
     */
    public function itemDownShelf(Request $request){
        $goods_id = $request->input('goods_id');
        $check_reason = $request->input('check_reason');
        if($goods_id && $check_reason){
            $goods = Goods::where([['id',$goods_id],['status',GoodsService::GOODS_STATUS_PUT],['is_delete',GoodsService::GOODS_NO_DELETE_STATUS]])
                ->select('id','status','ischeck','activity_type')->first();
            $goods = $goods ? $goods->toArray() : [];
            if(!empty($goods)){
                $res = Goods::where('id',$goods_id)->update(['status'=>GoodsService::GOODS_STATUS_VIOLATION_OFF,'ischeck'=>GoodsService::GOODS_CHECK_STATUS_NOT_SUBMIT,'is_shelf_check'=>GoodsService::GOODS_NO_SHELF_CHECK,'check_reason'=>$check_reason,'activity_type'=>'','update_time'=>time()]);
                if($res){
                    Redis::hdel(GoodsService::GOODS_INFO_KEY,$goods_id);
                    GoodsLog::AddGoodsLog($this->users['id'],$goods_id,'','商品违规下架','');
                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'操作成功');
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '操作失败');
                }
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '已上架的商品才能操作下架');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要下架的商品并填写下架原因');
        }
    }

    /**
     * 商品上架
     */
    public function goodsGrounding(Request $request){
        $goods_id = $request->input('goods_id');
        if($goods_id){
            $goods = Goods::where([['id',$goods_id],['is_delete',GoodsService::GOODS_NO_DELETE_STATUS]])
                ->select('id','status','ischeck','activity_type')->first();
            $goods = $goods ? $goods->toArray() : [];
            if(!empty($goods) && $goods['status'] == GoodsService::GOODS_STATUS_OFF ||$goods['status'] == GoodsService::GOODS_STATUS_VIOLATION_OFF ){
                $minPrices = GoodsRentSku::getMinPrice($goods_id);
                $data['min_price'] = $minPrices['min_price'];
                $data['min_line_price'] = $minPrices['min_line_price'];
                $data['min_lease_term'] = GoodsRentSku::getGoodsMinLeaseTerm($minPrices['meal_value_id']);
                $data['status'] = GoodsService::GOODS_STATUS_PUT;
                $data['ischeck'] = GoodsService::GOODS_CHECK_STATUS_CHECKED;
                $data['update_time'] = time();

                $res = Goods::where('id',$goods_id)->update($data);
                if($res){
                    //上架成功添加缓存
                    $goods = Goods::getGoodsInfo($goods_id);
                    if(!empty($goods)){
//                        $goods['month_rent'] = ceil($goods['min_price'] * 30);
//                        $goods['max_foregift'] = GoodsSetmeal::getMaxForegift($goods_id);
//                        $shop_category = CategoryUser::GetShopCategory($goods['member_id']);
//                        $goods['category'] = implode('、',array_column($shop_category,'name'));

                        Redis::hset(GoodsService::GOODS_INFO_KEY,$goods_id,json_encode($goods));
                    }
                    GoodsLog::AddGoodsLog($this->users['id'],$goods_id,'','商品上架','');
                    //租赁宝上传商品
//                    ZlbService::toTask([$goods_id],ZlbService::TYPE_GOODS);
                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'操作成功');
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '操作失败');
                }
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '已下架的商品才能操作上架');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要上架的商品');
        }
    }

    /**
     * 获取设置活动
     */
    public function getActivityList(Request $request){
        $goods_id = $request->input('goods_id');
        if($goods_id){
            $goods = Goods::where([['id',$goods_id],['status',GoodsService::GOODS_STATUS_PUT],['is_delete',GoodsService::GOODS_NO_DELETE_STATUS]])->select('id','activity_type')->first();
            $goods = $goods ? $goods->toArray() : [];
            if(!empty($goods)){
                $data['activity_list'] = GoodsService::GOODS_ACTIVITY_NAME_LIST;
                $data['activity_type'] = $goods['activity_type'];
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'操作成功',$data);
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '已上架的商品才能设置活动');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要操作的商品');
        }

    }


    /**
     * 设置活动
     */
    public function addActivity(Request $request){
        $goods_id = $request->input('goods_id');
        $activity_type = !empty($request->input('activity_type'))?$request->input('activity_type'):'';
        if($goods_id){
            $goods = Goods::where([['id',$goods_id],['status',GoodsService::GOODS_STATUS_PUT],['is_delete',GoodsService::GOODS_NO_DELETE_STATUS]])->select('id','activity_type')->first();
            $goods = $goods ? $goods->toArray() : [];
            if(!empty($goods)){
                if(!empty($activity_type) && !in_array($activity_type,GoodsService::GOODS_ACTIVITY_LIST)){
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '活动不存在');
                }
                $res = Goods::where('id',$goods_id)->update(['activity_type'=>$activity_type,'update_time'=>time()]);
                if($res){
                    GoodsLog::AddGoodsLog($this->users['id'],$goods_id,'','商品设置活动',json_encode($activity_type));
                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'设置成功');
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '设置失败');
                }
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '已上架的商品才能设置活动');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要操作的商品');
        }

    }

    /**
     * 添加商品基础信息
     */
    public function addGoodsData(Request $request2,GoodsSaveRequest $request){
        $data = $request->validated();
        if(empty($data)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '添加数据不能为空');
        }
        $data['status'] = GoodsService::GOODS_STATUS_OFF;
        $res = Goods::AddGoodsData($data,[],$request2['specData']);
        if($res){
            GoodsLog::AddGoodsLog($this->users['id'],$res['data']['goods_id'],'','添加商品基础信息',json_encode($data));
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'添加成功',['goods_id'=>$res]);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, $res['msg']);
        }
    }







}
